package org.glut.saltedfish.servlet;

import com.google.gson.Gson;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.glut.saltedfish.domain.User;
import org.glut.saltedfish.service.UserServiceImpl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * HDFuiny
 * 2025/7/16 12:33 2025 07
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // 设置响应类型和编码
        resp.setContentType("application/json;charset=utf-8");

        try (BufferedReader br = req.getReader();
             PrintWriter out = resp.getWriter()) {

            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                stringBuilder.append(line);
            }
            String json = stringBuilder.toString();

            // 反序列化接收的JSON
            Gson gson = new Gson();
            User loginUser = gson.fromJson(json, User.class);

            // 验证登录
            boolean success = UserServiceImpl.login(loginUser);

            if (success) {
                // 登录成功后，获取用户完整信息（假设根据手机号查询）
                User fullUserInfo = UserServiceImpl.getUserByPhone(loginUser.getPhone());

                if (fullUserInfo != null) {
                    // 构建包含用户完整信息的响应
                    Map<String, Object> result = new HashMap<>();
                    result.put("code", 200);
                    result.put("msg", "登录成功");
                    result.put("data", fullUserInfo); // 将完整用户对象放入data字段

                    // 使用Gson将Map序列化为JSON
                    out.write(gson.toJson(result));
                } else {
                    // 理论上不会执行到这里，因为login已验证成功
                    out.write("{\"code\":409,\"msg\":\"用户名或密码错误\"}");
                }
            } else {
                out.write("{\"code\":409,\"msg\":\"用户名或密码错误\"}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.setStatus(500);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }
}